﻿@page "/"
@page "/Nodes"
@using iPanel.Components.ResourcesGridColumns
@using iPanel.Resources
@using iPanel.Utils
@using System.Globalization
@using iPanel.Components.Controls.Grid
@using iPanel.Model
@using Humanizer
@implements IDisposable
@inject IStringLocalizer<iPanel.Resources.Resources> Loc
@inject IStringLocalizer<ControlsStrings> ControlsStringsLoc
@inject BrowserTimeProvider TimeProvider

<PageTitle><ApplicationName ResourceName="@nameof(iPanel.Resources.Resources.ResourcesPageTitle)" Loc="@Loc" /></PageTitle>

@code {
    private const string TypeColumn = nameof(TypeColumn);
    private const string NameColumn = nameof(NameColumn);
    private const string StateColumn = nameof(StateColumn);
    private const string StartTimeColumn = nameof(StartTimeColumn);
    private const string SourceColumn = nameof(SourceColumn);
    private const string UrlsColumn = nameof(UrlsColumn);
    private const string ActionsColumn = nameof(ActionsColumn);
    private ColumnResizeLabels _resizeLabels = ColumnResizeLabels.Default;
    private ColumnSortLabels _sortLabels = ColumnSortLabels.Default;
    private readonly CancellationTokenSource cancellationTokenSource = new();

    private string _filter = "";
    [CascadingParameter]
    public required ViewportInformation ViewportInformation { get; set; }
    [Inject]
    public required TelemetryRepository TelemetryRepository { get; init; }
    [Inject]
    public required NavigationManager NavigationManager { get; init; }
    private FluentDataGrid<OtlpResourceView> _dataGrid = null!;
    protected override async Task OnInitializedAsync()
    {
        StateHasChanged();
        TelemetryRepository.OnResourceChanges(async a =>
        {
            await InvokeAsync(async () =>
                    {
                        await _dataGrid.SafeRefreshDataAsync();
                        StateHasChanged();
                    });
        }, cancellationTokenSource.Token);


    }
    private async Task HandleSearchFilterChangedAsync()
    {
        await _dataGrid.SafeRefreshDataAsync();
    }

    private ValueTask<GridItemsProviderResult<OtlpResourceView>> GetData(GridItemsProviderRequest<OtlpResourceView> request)
    {
        var resources = TelemetryRepository.GetResources();
        return ValueTask.FromResult(GridItemsProviderResult.From(resources, resources.Count));
    }

    public async Task GoConsoleAsync(string id)
    {
        NavigationManager.NavigateTo($"/consolelogs/resource/{id}", false);
    }

    public void Dispose()
    {
        cancellationTokenSource?.Cancel();
        cancellationTokenSource?.Dispose();
    }
}

<div class="page-content-container">
    <AspirePageContentLayout IsSummaryDetailsViewOpen="@false">
        <PageTitleSection>
            <h1 class="page-header">@Loc[nameof(iPanel.Resources.Resources.ResourcesHeader)]</h1>
        </PageTitleSection>

        @* <ToolbarSection>
            <FluentSearch Placeholder="@ControlsStringsLoc[nameof(ControlsStrings.FilterPlaceholder)]"
                          Immediate="true"
                          ImmediateDelay="@FluentUIExtensions.InputDelay"
                          @bind-Value="_filter"
                          slot="end"
                          Label=remove"@(ViewportInformation.IsDesktop ? null : ControlsStringsLoc[nameof(ControlsStrings.FilterPlaceholder)].Value)"
                          @bind-Value:after="HandleSearchFilterChangedAsync" />
            <FluentDivider slot="end" Role="DividerRole.Presentation" Orientation="Orientation.Vertical" />
        </ToolbarSection> *@

        <MainSection>
            <div class="resources-summary-layout">
                <div class="resources-grid-container">
                    <FluentDataGrid @ref="_dataGrid"
                                    ColumnResizeLabels="@_resizeLabels"
                                    ColumnSortLabels="@_sortLabels"
                                    HeaderCellAsButtonWithMenu="true"
                                    ResizeType="DataGridResizeType.Discrete"
                                    Virtualize="true"
                                    GenerateHeader="GenerateHeaderOption.Sticky"
                                    ItemSize="46"
                                    ItemsProvider="@GetData"
                                    ResizableColumns="true"
                                    RowClass="@(r => "resource-row")"
                                    ShowHover="true"
                                    TGridItem="OtlpResourceView"
                                    ItemKey="@(r => r.NodeId)"
                                    OnRowClick="@(r => r.ExecuteOnDefault(d => GoConsoleAsync(d.NodeId))  )"
                                    Class="main-grid enable-row-click">
                        <ChildContent>
                            <PropertyColumn Width="350px" Title="名称" Property="@(c => ShortName.Application(c.NodeId))" />
                            <AspireTemplateColumn Width="150px" Title="IP" Tooltip="true" TooltipText="(e) => e.Ip">
                                <IpColumnDisplay FilterText="@(string.Empty)" Entry="@context" />
                            </AspireTemplateColumn>
                            <PropertyColumn Title="CPU" Property="@(c => c.Cpu)" />
                            <PropertyColumn Title="进程内存" Property="@(c => c.ProcessMem)" />
                            <PropertyColumn Title="可用内存" Property="@(c => string.Format("{0}/{1}",c.AvailableMemory,c.TotalMem))" />
                            <PropertyColumn Title="可用磁盘" Property="@(c => string.Format("{0}/{1}",c.AvailableDiskSpace,c.TotalDisk))" />
                            <PropertyColumn Title="上传" Property="@(c => c.UpTcp)" />
                            <PropertyColumn Title="下载" Property="@(c => c.DownTcp)" />
                            <PropertyColumn Title="更新时间" Property="@(c => FormatHelpers.FormatTimeWithOptionalDate(TimeProvider, c.ModifyAt, MillisecondsDisplay.Truncated,null))" />
                            <PropertyColumn Title="注册时间" Property="@(c => FormatHelpers.FormatTimeWithOptionalDate(TimeProvider, c.CreateAt, MillisecondsDisplay.Truncated,null))" />
                            @* <PropertyColumn Width="200px" Title="IP" Property="@(c => c.Ip)" /> *@

                        </ChildContent>
                        <EmptyContent>
                            <FluentIcon Icon="Icons.Regular.Size24.AppGeneric" />&nbsp;@Loc[nameof(iPanel.Resources.Resources.ResourcesNoResources)]
                        </EmptyContent>
                    </FluentDataGrid>
                </div>
            </div>
        </MainSection>
    </AspirePageContentLayout>
</div>

